import CodeBlock from "../../../component/CodeBlock";
import React, { useReducer } from "react";

// 基础示例：计数器
const CounterReducer = () => {
  // 定义reducer函数
  const reducer = (state: number, action: { type: string }) => {
    switch (action.type) {
      case 'increment':
        return state + 1;
      case 'decrement':
        return state - 1;
      case 'reset':
        return 0;
      default:
        return state;
    }
  };

  // 使用useReducer管理状态
  const [count, dispatch] = useReducer(reducer, 0);

  return (
    <div style={{ padding: "20px", border: "1px solid #ddd", borderRadius: "5px", marginTop: "10px" }}>
      <h3>计数器示例</h3>
      <p>当前计数: {count}</p>
      <button 
        onClick={() => dispatch({ type: 'increment' })}
        style={{ marginRight: "10px" }}
      >
        增加
      </button>
      <button 
        onClick={() => dispatch({ type: 'decrement' })}
        style={{ marginRight: "10px" }}
      >
        减少
      </button>
      <button onClick={() => dispatch({ type: 'reset' })}>
        重置
      </button>
      <CodeBlock language="javascript" code={`import React, { useReducer } from "react";

const reducer = (state, action) => {
  switch (action.type) {
    case 'increment':
      return state + 1;
    case 'decrement':
      return state - 1;
    case 'reset':
      return 0;
    default:
      return state;
  }
};

const Counter = () => {
  const [count, dispatch] = useReducer(reducer, 0);
  
  return (
    <div>
      <p>当前计数: {count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>增加</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>减少</button>
      <button onClick={() => dispatch({ type: 'reset' })}>重置</button>
    </div>
  );
};

export default Counter;`} />
    </div>
  );
};

// 复杂示例：表单状态管理
const FormReducer = () => {
  // 定义表单状态
  const initialState = {
    name: '',
    email: '',
    password: '',
    errors: {
      name: '',
      email: '',
      password: ''
    }
  };

  // 定义reducer函数
  const formReducer = (state: any, action: any) => {
    switch (action.type) {
      case 'HANDLE_INPUT_CHANGE':
        return {
          ...state,
          [action.field]: action.value
        };
      case 'VALIDATE_FORM':
        const errors = {
          name: action.value.name.length < 3 ? '姓名至少需要3个字符' : '',
          email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(action.value.email) ? '' : '请输入有效的邮箱地址',
          password: action.value.password.length < 6 ? '密码至少需要6个字符' : ''
        };
        
        return {
          ...action.value,
          errors
        };
      case 'RESET_FORM':
        return initialState;
      default:
        return state;
    }
  };

  // 使用useReducer管理表单状态
  const [state, dispatch] = useReducer(formReducer, initialState);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const validatedState = formReducer(state, { 
      type: 'VALIDATE_FORM', 
      value: state 
    });
    
    // 检查是否有错误
    const hasErrors = Object.values(validatedState.errors).some(error => error !== '');
    
    if (!hasErrors) {
      alert('表单提交成功!');
      dispatch({ type: 'RESET_FORM' });
    } else {
      dispatch({ 
        type: 'VALIDATE_FORM', 
        value: validatedState 
      });
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    dispatch({
      type: 'HANDLE_INPUT_CHANGE',
      field: e.target.name,
      value: e.target.value
    });
  };

  return (
    <div style={{ padding: "20px", border: "1px solid #ddd", borderRadius: "5px", marginTop: "20px" }}>
      <h3>表单状态管理示例</h3>
      <form onSubmit={handleSubmit}>
        <div style={{ marginBottom: "15px" }}>
          <label>姓名: </label>
          <input
            type="text"
            name="name"
            value={state.name}
            onChange={handleInputChange}
            style={{ width: "200px", padding: "5px" }}
          />
          {state.errors.name && <div style={{ color: "red" }}>{state.errors.name}</div>}
        </div>
        
        <div style={{ marginBottom: "15px" }}>
          <label>邮箱: </label>
          <input
            type="email"
            name="email"
            value={state.email}
            onChange={handleInputChange}
            style={{ width: "200px", padding: "5px" }}
          />
          {state.errors.email && <div style={{ color: "red" }}>{state.errors.email}</div>}
        </div>
        
        <div style={{ marginBottom: "15px" }}>
          <label>密码: </label>
          <input
            type="password"
            name="password"
            value={state.password}
            onChange={handleInputChange}
            style={{ width: "200px", padding: "5px" }}
          />
          {state.errors.password && <div style={{ color: "red" }}>{state.errors.password}</div>}
        </div>
        
        <button type="submit" style={{ padding: "8px 15px", background: "#4CAF50", color: "white", border: "none", borderRadius: "4px" }}>
          提交
        </button>
      </form>
      
      <CodeBlock language="javascript" code={`import React, { useReducer } from "react";

const initialState = {
  name: '',
  email: '',
  password: '',
  errors: {
    name: '',
    email: '',
    password: ''
  }
};

const formReducer = (state, action) => {
  switch (action.type) {
    case 'HANDLE_INPUT_CHANGE':
      return {
        ...state,
        [action.field]: action.value
      };
    case 'VALIDATE_FORM':
      const errors = {
        name: action.value.name.length < 3 ? '姓名至少需要3个字符' : '',
        email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(action.value.email) ? '' : '请输入有效的邮箱地址',
        password: action.value.password.length < 6 ? '密码至少需要6个字符' : ''
      };
      
      return {
        ...action.value,
        errors
      };
    case 'RESET_FORM':
      return initialState;
    default:
      return state;
  }
};

const Form = () => {
  const [state, dispatch] = useReducer(formReducer, initialState);
  
  const handleSubmit = (e) => {
    e.preventDefault();
    const validatedState = formReducer(state, { 
      type: 'VALIDATE_FORM', 
      value: state 
    });
    
    // 检查是否有错误
    const hasErrors = Object.values(validatedState.errors).some(error => error !== '');
    
    if (!hasErrors) {
      alert('表单提交成功!');
      dispatch({ type: 'RESET_FORM' });
    } else {
      dispatch({ 
        type: 'VALIDATE_FORM', 
        value: validatedState 
      });
    }
  };
  
  const handleInputChange = (e) => {
    dispatch({
      type: 'HANDLE_INPUT_CHANGE',
      field: e.target.name,
      value: e.target.value
    });
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>姓名: </label>
        <input
          type="text"
          name="name"
          value={state.name}
          onChange={handleInputChange}
        />
        {state.errors.name && <div style={{ color: "red" }}>{state.errors.name}</div>}
      </div>
      
      <div>
        <label>邮箱: </label>
        <input
          type="email"
          name="email"
          value={state.email}
          onChange={handleInputChange}
        />
        {state.errors.email && <div style={{ color: "red" }}>{state.errors.email}</div>}
      </div>
      
      <div>
        <label>密码: </label>
        <input
          type="password"
          name="password"
          value={state.password}
          onChange={handleInputChange}
        />
        {state.errors.password && <div style={{ color: "red" }}>{state.errors.password}</div>}
      </div>
      
      <button type="submit">提交</button>
    </form>
  );
};

export default Form;`} />
    </div>
  );
};

// 介绍useReducer
function UseReducer() {
  return (
    <div style={{ maxWidth: "800px", margin: "0 auto", padding: "20px" }}>
      <h1>useReducer 使用指南</h1>
      
      <div style={{ marginTop: "20px", lineHeight: "1.6" }}>
        <h2>什么是 useReducer？</h2>
        <p>
          <code>useReducer</code> 是 React 提供的一个 Hook，用于组件的状态管理。
          它是 <code>useState</code> 的替代方案，特别适用于处理复杂的状态逻辑，
          或者当多个状态值之间相互依赖时。
        </p>
        
        <h2>什么时候使用 useReducer？</h2>
        <ul>
          <li>状态逻辑复杂且包含多个子值</li>
          <li>下一个状态依赖于前一个状态</li>
          <li>需要处理多个相关的状态更新</li>
          <li>状态更新逻辑需要重用</li>
          <li>希望将状态更新逻辑与组件分离</li>
        </ul>
        
        <h2>useReducer 基本语法</h2>
        <CodeBlock language="javascript" code={`const [state, dispatch] = useReducer(reducer, initialState);`} />
        <p>参数说明：</p>
        <ul>
          <li><code>reducer</code>: 一个函数，接收当前状态和动作(action)，返回新状态</li>
          <li><code>initialState</code>: 初始状态</li>
          <li>返回值: 包含两个元素的数组，第一个是当前状态，第二个是dispatch函数</li>
        </ul>
        
        <h2>Reducer 函数</h2>
        <p>Reducer函数的基本结构：</p>
        <CodeBlock language="javascript" code={`(state, action) => {
  switch (action.type) {
    case 'action_type_1':
      return /* 新状态 */;
    case 'action_type_2':
      return /* 新状态 */;
    default:
      return state;
  }
};`} />
        <p>Reducer函数应该遵循以下原则：</p>
        <ul>
          <li>返回新对象而不是直接修改原状态</li>
          <li>对于相同输入总是返回相同输出</li>
          <li>只处理与action类型相关的状态更新</li>
        </ul>
        
        <h2>Dispatch 函数</h2>
        <p>Dispatch函数用于触发状态更新：</p>
        <CodeBlock language="javascript" code={`dispatch({ type: 'action_type', payload: 'data' });`} />
        <p>参数说明：</p>
        <ul>
          <li><code>type</code>: 动作类型，用于在reducer中匹配相应的处理逻辑</li>
          <li><code>payload</code>: 可选，传递给reducer的数据</li>
        </ul>
        
        <h2>useReducer 与 useState 的区别</h2>
        <ul>
          <li>useState 适用于简单状态，useReducer 适用于复杂状态</li>
          <li>useState 更简洁，useReducer 提供更可预测的状态管理</li>
          <li>useState 更适合独立的状态值，useReducer 更适合相互关联的状态</li>
          <li>useReducer 可以更好地测试状态逻辑，因为reducer是纯函数</li>
        </ul>
      </div>
      
      <CounterReducer />
      <FormReducer />
    </div>
  );
}

export default UseReducer;